package com.example.demo.itext;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import org.apache.commons.io.IOUtils;

import java.io.*;

public class PdfTest {
    public static void main(String[] args) throws IOException, DocumentException {
        byte[] pdfBytes=IOUtils.toByteArray(new FileInputStream("F:\\360MoveData\\Users\\lqq\\Desktop\\image\\航空保险报销凭证.pdf"));
        byte[] pdfBytes2=IOUtils.toByteArray(new FileInputStream("F:\\360MoveData\\Users\\lqq\\Desktop\\image\\南宁-重庆机票.pdf"));
//        byte[] pdfBytes = IOUtils.toByteArray(inputStream);
        PdfReader.unethicalreading=true;
        PdfReader pdfReader = new PdfReader(pdfBytes);
        com.itextpdf.text.Document mergedDoc = new com.itextpdf.text.Document(pdfReader.getPageSize(1));
        OutputStream os=new FileOutputStream("F:\\360MoveData\\Users\\lqq\\Desktop\\image\\合并发票.pdf");
        PdfCopy copy = new PdfCopy(mergedDoc, os);
        PdfReader reader = new PdfReader(pdfBytes2);
        // 获取页数
        int numberOfPages = reader.getNumberOfPages();
        // 从第一页开始
        for (int i = 1; i <= numberOfPages; i++) {
            // 新建文档页
            mergedDoc.newPage();
            // 复制操作
            PdfImportedPage page = copy.getImportedPage(reader, i);
            copy.addPage(page);
        }
        os.flush();
        os.close();
    }

}
